package com.atguigu.day01;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

public class Flink02_Stream_Bounded_WordCount {
    public static void main(String[] args) throws Exception {
//        1.创建flink的流处理环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        //将并行度设置为1
        env.setParallelism(1);

//        2.读取文件数据 textFile
        DataStreamSource<String> streamSource = env.readTextFile("input/word.txt");

//        3.按照空格切分出每一个单词 flatmap
        SingleOutputStreamOperator<String> wordsDStream = streamSource.flatMap(new FlatMapFunction<String, String>() {
            @Override
            public void flatMap(String value, Collector<String> out) throws Exception {
                String[] words = value.split(" ");
                for (String word : words) {
                    out.collect(word);
                }
            }
        });

//        4.将每一个单词转为Tuple2元组<单词（String），1（Integer）>   lambda写法
        SingleOutputStreamOperator<Tuple2<String, Integer>> wordToOneDStream = wordsDStream.map(value -> Tuple2.of(value, 1))
                //这里会遇到泛型擦除问题 原因是因为用了lambda表达式解决方式如下
                .returns(Types.TUPLE(Types.STRING,Types.INT))
                ;

//        5.先按照单词聚合
        KeyedStream<Tuple2<String, Integer>, String> keyedStream = wordToOneDStream.keyBy(new KeySelector<Tuple2<String, Integer>, String>() {
            /**
             * 通过这个方法来指定key
             * @param value 操作的数据
             * @return
             * @throws Exception
             */
            @Override
            public String getKey(Tuple2<String, Integer> value) throws Exception {
                return value.f0;
            }
        });

//        6.累加
        SingleOutputStreamOperator<Tuple2<String, Integer>> result = keyedStream.sum(1);

        result.print();

        //在flink中，每调用一个execute就会有一个job
        env.execute();
    }
}
